package com.qingxin.sys.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.ServletContextAware;

import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.SysUserService;
import com.qingxin.sys.support.SystemCfg;

@Controller
public class BaseAction implements ServletContextAware {

	@Autowired
	protected SysUserService sysUserService;
	
	protected ServletContext servletContext;
	
	
	/**
	 * 日志记录对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	
	/**
	 * 获取登录用户信息，如果用户没有登录返回null
	 * @param request
	 * @return
	 */
	protected LoginUser getLoginUser(HttpServletRequest request){
		String userid = (String) request.getSession().getAttribute(SystemCfg.SESSION_LOGIN_USERID);
		if(userid == null){
			return null;
		}
		LoginUser loginUser = sysUserService.getLoginUser(userid);
		return loginUser;
	}
	
	
	
	protected List<SysError> getSysErrors(BindingResult result){
		List<SysError> list = new ArrayList<SysError>();
		List<ObjectError> errors = result.getAllErrors();
		if(list!=null){
			for(ObjectError error : errors){
				list.add(new SysError(error.getDefaultMessage()));
			}
		}
		return list;
	}
	
	
	protected void downloadFile(File file, String fileName, HttpServletResponse response) throws Exception {
		fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		response.resetBuffer();
		String fn = file.getName().toLowerCase();
		if(fn.endsWith(".doc")){
			response.setContentType("application/msword; charset=UTF-8");
		}else if(fn.endsWith(".docx")){
			response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=UTF-8");
		}else if(fn.endsWith(".xls")){
			response.setContentType("application/vnd.ms-excel; charset=UTF-8");
		}else if(fn.endsWith(".xlsx")){
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
		}else if(fn.endsWith(".ppt")){
			response.setContentType("application/vnd.ms-powerpoint; charset=UTF-8");
		}else if(fn.endsWith(".pptx")){
			response.setContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation; charset=UTF-8");
		}else if(fn.endsWith(".pdf")){
			response.setContentType("application/pdf; charset=UTF-8");
		}else if(fn.endsWith(".txt")){
			response.setContentType("text/plain; charset=UTF-8");
		}else if(fn.endsWith(".rtf")){
			response.setContentType("application/x-rtf; charset=UTF-8");
		}else{
			response.setContentType("application/octet-stream; charset=UTF-8");
		}
		response.setHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + fileName);
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buf = new byte[4096];
			int n = 0;
			while ((n = bis.read(buf))!=-1){
				bos.write(buf, 0, n);
			}
		} finally {
			if(bis!=null){
				try {
					bis.close();
				} catch (Exception e2) {}
			}
			if(bos!=null){
				try {
					bos.close();
				} catch (Exception e2) {}
			}
		}
	}
	
	
}
